9. 热门搜索换页

点击换一换按钮,实现热门搜索的更新(分页)

common/header/store/reducer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const defaultState = fromJS({
showSearchArea: '',
list: [],
page: 1, // 默认页码
totalPage: 1, // 默认总页数
mouseIn: false // 鼠标是否在上面
});

...
...
export default (state = defaultState, action ) => {
switch(action.type){
// 获得焦点,将showSearchArea的值设置为true
case constants.SEARCH_FOCUS:
return state.set('showSearchArea', true)

// 失去焦点,将showSearchArea的值设置为false
case constants.SEARCH_BLUR:
return state.set('showSearchArea', false)

// 获取热门搜索的值
case constants.CHANGE_LIST:
// return state.set('list', action.data).set('totalPage', action.totalPage)
// 下面写法和上面一样的结果一样,merge相当于实现多个set
return state.merge({
'list': action.data,
'totalPage': action.totalPage
})

// mouseEnter
case constants.MOUSE_ENTER:
return state.set('mouseIn', true)

// mouseLeave
case constants.MOUSE_LEAVE:
return state.set('mouseIn', false)

// 更换页码
case constants.CHANGE_PAGE:
return state.set('page', action.page)

default:
return state;
}
}

state.set只能为一个state对象设置值,如果我们想为多个设置的时候,可以使用merge

common/header/store/actionCreator.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const mouseEnter = () => ({
type: constants.MOUSE_ENTER
});

export const mouseLeave = () => ({
type: constants.MOUSE_LEAVE
});

export const changePage = (page) => ({
type: constants.CHANGE_PAGE,
page
});

const changeList = (data) => ({
type: constants.CHANGE_LIST,
data: fromJS(data),
totalPage: Math.ceil(data.length / 10)
});

点击换一换的时候,将当前页面和总页面传入handleChangePage函数,在里面进行比较,如果当前页小于总页数,那么就将当前页加一,并传入reducer进行修改,否则就修改为第一页
common/header/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (showSearchArea || mouseIn){
return (
<Searchinfo
onMouseEnter={ handleMouseEnter }
onMouseLeave={ handleMouseLeave }
>
<SearchInfoTitle>
热门搜索
<SearchInfoSwitch
onClick={()=> handleChangePage(page, totalPage)}>
换一换
</SearchInfoSwitch>
</SearchInfoTitle>

<SearchInfoList>
{ pageList }
</SearchInfoList>
</Searchinfo>
)
}else{
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const mapDispathToProps = (dispatch) => {
return {
// 获得焦点,派发dispatch函数
SearchFocus(){
// 获取异步数据
dispatch(actionCreator.getList())
dispatch(actionCreator.searchFocus())
},

// 失去焦点,派发dispatch函数
SearchBlur(){
dispatch(actionCreator.searchBlur())
},

// 鼠标在上面
handleMouseEnter(){
dispatch(actionCreator.mouseEnter())
},

// 鼠标被移除
handleMouseLeave(){
dispatch(actionCreator.mouseLeave())
},

// 点击换一换更换页码
handleChangePage(page, totalPage){
if (page < totalPage){
dispatch(actionCreator.changePage(page + 1))
}else{
dispatch(actionCreator.changePage(1))
}

}
}
}

代码地址